package com.ozo.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozo.easy.entity.SysMenu;
import com.ozo.easy.entity.SysRoleMenu;
import com.ozo.easy.mapper.SysMenuMapper;
import com.ozo.easy.mapper.SysRoleMenuMapper;
import com.ozo.easy.pojo.dto.SysRoleMenuAuthDTO;
import com.ozo.easy.pojo.vo.SysMenuVO;
import com.ozo.easy.service.ISysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色菜单 服务实现类
 *
 * @author ozo
 * @version 1.0
 * @date 2025-02-17 16:53:43
 */
@RequiredArgsConstructor
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    private final SysMenuMapper sysMenuMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void auth(SysRoleMenuAuthDTO menuAuthDTO) {
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, menuAuthDTO.getRoleId());
        baseMapper.delete(queryWrapper);

        List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
        for (Long menuId : menuAuthDTO.getMenuIdList()) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(menuAuthDTO.getRoleId());
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuList.add(sysRoleMenu);
        }
        this.saveBatch(sysRoleMenuList);
    }

    @Override
    public List<SysMenuVO> detail(Long id) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysMenu::getOrderNum);
        List<SysMenu> recordList = sysMenuMapper.selectList(queryWrapper);

        LambdaQueryWrapper<SysRoleMenu> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SysRoleMenu::getRoleId, id);
        List<Long> menuIdList = baseMapper.selectList(queryWrapper1).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());

        List<SysMenuVO> recordVOList = BeanUtil.copyToList(recordList, SysMenuVO.class);
        for (SysMenuVO sysMenuVO : recordVOList) {
            List<SysMenuVO> collect = recordVOList.stream().filter(e -> sysMenuVO.getId().equals(e.getParentId())).collect(Collectors.toList());
            sysMenuVO.setChildren(collect);
            sysMenuVO.setChecked(menuIdList.contains(sysMenuVO.getId()));
        }

        return recordVOList.stream().filter(e -> e.getParentId() == null).collect(Collectors.toList());
    }

}
